#!/usr/bin/env python
# -*- coding: UTF-8 -*-

import urllib,urllib2,re,xbmcplugin,xbmcgui,xbmc,xbmcaddon,HTMLParser,os,sys,time

addon_id = 'plugin.video.adultstv'
selfAddon = xbmcaddon.Addon(id=addon_id)
addonfolder = selfAddon.getAddonInfo('path')
artfolder = addonfolder + '/resources/img/'

base_url = 'https://raw.githubusercontent.com/AiWABR/list2/master/Main.xml'
no_image = 'https://corsetsandcutlasses.files.wordpress.com/2013/12/cover-not-yet-available.jpg'
delImage = 'http://www.muziejusalka.lt/files/upload/big_D%C4%97mesio.png'
retry_image = 'http://cdn3.iconfinder.com/data/icons/3d-printing-icon-set/256/Refresh.png'

def menu():
	xml = abrir_url(base_url)
	menu = re.findall(r'<folder>(.*?)</folder>.*?<url>(.*?)</url>.*?<img>(.*?)</img>', xml, re.DOTALL)
	for name, url, img in menu:
		addDir(name, url, 301, img)

def listar_videos(url):
	html = abrir_url(url)
	
	folder_items = re.findall(r'<foldename>(.*?)</foldername>.*?<thumb>(.*?)</thumb>.*?<url>(.*?)</url>.*?<background>(.*?)</background>', html, re.I|re.DOTALL)
	items = re.findall(r'<name>(.*?)</name>.*?<thumb>(.*?)</thumb>.*?<url>(.*?)</url>', html, re.I|re.DOTALL)

	if folder_items:
		for folder_name, thumb, url, folder_fanart in folder_items:
			addDir(folder_name, url, 301, thumb)
			
	if items:
		totalitems = len(items)
		for name, thumb, url in items:
			addDir(name, url, 302, thumb, False, totalitems)
		
def play(name, url, iconimage):
	mensagemprogresso = xbmcgui.DialogProgress()
	mensagemprogresso.create('Adults TV', 'A resolver link.', 'Por favor aguarde...')
	alt_url = ''
	
	if re.search('\<ALT\>', url):
		r = re.split('\<ALT>', url)
		url = str(r[0])
		alt_url = str(r[1])
	
	if re.search('\.mp4', url, re.I):
		stream_url = url
	else:
		import urlresolver
		stream_url = urlresolver.HostedMediaFile(url=url).resolve()
		print 'casrarasf'
		print stream_url
		if not stream_url or not isinstance(stream_url, basestring):
			if alt_url != '': 
				play(name, alt_url, iconimage)
			else:
				xbmcgui.Dialog().ok("Erro!","Impossível abrir vídeo")
				mensagemprogresso.close()
			return
	
	mensagemprogresso.close()
	listitem = xbmcgui.ListItem(path=str(stream_url), iconImage=iconimage, thumbnailImage=iconimage)
	listitem.setProperty('IsPlayable', 'true')
	listitem.setPath(str(stream_url))
	xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, listitem)
	player = xbmc.Player(xbmc.PLAYER_CORE_AUTO)
	player.play(str(stream_url),listitem)
	
def mode(mode,name,url,iconimage):
	if mode == 300: menu()
	elif mode == 301: listar_videos(url)
	elif mode == 302: play(name, url, iconimage)
	
def addDir(name,url,mode,iconimage,pasta = True,total=1):
	u=sys.argv[0]+"?url="+urllib.quote_plus(url)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)+"&iconimage="+urllib.quote_plus(iconimage)
	ok=True
	liz=xbmcgui.ListItem(name, iconImage="DefaultFolder.png", thumbnailImage=iconimage)
	liz.setProperty('fanart_image', addonfolder + '/fanart.jpg')
	ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=pasta,totalItems=total)
	return ok
	
def abrir_url(url):
	req = urllib2.Request(url)
	req.add_header('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3')
	response = urllib2.urlopen(req)
	link=response.read()
	response.close()
	return link